package com.letv.download;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.letv.bean.SummaryBean;
import com.letv.common.Constants;
import com.letv.common.Mappings;
import com.letv.common.ProcessData;
import com.letv.conf.ConfigFactory;
import com.letv.util.SQLUtil;

public class DownloadMapperService implements DownloadService{

    private static final Logger logger = LoggerFactory.getLogger(DownloadMapperService.class);
    
    // 外网取单视频流截图时的默认排序
    private static final String[] ARRAy_SORT = {"400*225",
                                                "320*180",
                                                "960*540",
                                                "1440*810",
                                                "145*82",
            "480*360",
                                                "216*122",
                                                "400*300",
                                                "640*360"};
    private static final String[] IMAGES_KEY = { "400*225", "960*540", "1080*608", "1440*810" };

    /**
     * String[], tv牌照方站点源所需横图尺寸
     */
    private static final String[] TV_LICENSE_TRANSVERSE_IMAGE_KEY = {"400*225", "960*540"};
 
	@Override
	public SummaryBean down(String type) {
		return null;
	}

	@Override
	public SummaryBean downLesoExtraet(String type) {
		return null;
	}

	@Override
	public boolean downDataById(String type, int id) {
		return false;
	}

	@Override
	public boolean delDataById(String type, int id) {
		return false;
	}

	@Override
	public boolean updDataById(String type, int id) {
		return false;
	}
	protected boolean isContinue;

	public boolean isContinue() {
		return isContinue;
	}

	public void setContinue(boolean isContinue) {
		this.isContinue = isContinue;
	}

	protected String mapperVideoList(Connection connToSrc, Map<String, Object> m) throws SQLException {
		ArrayList<Map<String, Object>> videolists;
		String vid = m.get("vid").toString();
		String source= m.get("source").toString();
		boolean isLetv = Constants.WEBSITE_LETV.equals(source);
		boolean isEros = Constants.WEBSITE_EROS.equals(source);
		boolean isCibn = Constants.WEBSITE_CIBN.equals(source);
		boolean isImgoOnTv = Constants.WEBSITE_IMGO.equals(source) && null != m.get("is_cibn_checked") && "1".equals(m.get("is_cibn_checked").toString());
		boolean isWasu_tv = Constants.WEBSITE_WASUTV.equals(source);
		boolean isShows = Constants.WEBSITE_SHOWS.equalsIgnoreCase(source);
	    String category = m.get("category").toString();
        Object contentType = m.get("content_type");
        //boolean hasDuration = ConfigFactory.getString("leso.hasDurationSources").indexOf(source) >= 0 ? true : false;
        boolean hasPreview = ConfigFactory.getString("leso.hasPreviewSources").indexOf(source) >= 0 ? true : false;
        if (hasPreview) {
            List<String> params = Arrays.asList(new String[] { "180001", "180002" });
            videolists = SQLUtil.getLesoAlbumVideoSourceData(connToSrc, "leso.getSingleVideo", vid, params);
        } else if (contentType != null
                && String.valueOf(Constants.CONTENT_TYPE_YOUTUBE_PLAYLIST).equals(contentType.toString())) {
            videolists = SQLUtil.getLesoAlbumVideoSourceData(connToSrc, "leso.getYoutubeSingleVideo", vid);
        } else {
		    videolists = SQLUtil.getLesoAlbumVideoSourceData(connToSrc, "leso.SQL3", vid,"180001");
		}
		if (videolists.size() == 0 && isLetv) {
		    videolists = getOtherTypeVideo(connToSrc, "leso.SQL3", vid);
		}
		if (videolists.size() == 0 && isEros) {    // 若当前无eros正片则尝试取eros预告片
		    videolists = SQLUtil.getLesoAlbumVideoSourceData(connToSrc, "leso.SQL3", vid,"180002");
		}
		if( videolists.size()  == 0) {
			this.isContinue=true;
			return "single_video don't have data,video_id="+vid;
		}

        Object cpId = m.get("cp_info_id");
        if (cpId != null) {
            setPublisher(cpId, connToSrc, m);
        }
        boolean desc = category.equals("4") || category.equals("16") || category.equals("101")
                || category.equals("1004");
		StringBuffer tempUrls = new StringBuffer();
		StringBuffer tempIntro = new StringBuffer("");
		StringBuffer deadlinks = new StringBuffer("");

		// old singleVideo uniqueID : this id will be coexistence with resource ID for a long time -- 20160823
		StringBuffer globalVid = new StringBuffer("");
		// LeEco Resource ID : LeEco ID and Self System ID(leso single video id) connected by "_"
		StringBuffer letv_orininal_svids = new StringBuffer("");

	    StringBuffer videoSubNames = new StringBuffer("");
	    StringBuffer singleVideoImages = new StringBuffer("");
        StringBuffer isPays = new StringBuffer("");
        StringBuffer downloadPlatform = new StringBuffer("");
        StringBuffer payPlatform = new StringBuffer("");
        StringBuffer exterenalIds = new StringBuffer("");
        StringBuffer externalPlayIds = new StringBuffer("");
        StringBuffer midsb = new StringBuffer("");
        StringBuffer letvids = new StringBuffer("");
        StringBuffer videoIds = new StringBuffer("");
        StringBuilder videoDurations = new StringBuilder("");
        StringBuilder videoTypes = new StringBuilder("");
        Map<String, String> cmsImages = new HashMap<String, String>();
		int i = desc?videolists.size()-1:0;
		int end = desc?0:videolists.size()-1;
		do {
			Map<String, Object> transientMap=videolists.get(i);
			Object episodetmp = transientMap.get("episode");
			Object mid = transientMap.get("mid");
			strAppend(tempUrls, episodetmp, transientMap.get("play_link").toString(),";");
			strAppend(deadlinks, episodetmp, transientMap.get("deadlinks").toString(),";");
			strAppend(globalVid, episodetmp, transientMap.get("global_vid"),";");
			strAppend(letv_orininal_svids, episodetmp, this.connectVideoResourceId(transientMap, isLetv),";");
            videoIds.append(transientMap.get("svid")).append(",");
            videoTypes.append(transientMap.get("type")).append(",");
            
            videoDurations.append(transientMap.get("duration_second") == null ? "" : transientMap.get("duration_second")).append(",");
            
            JSONObject json = null;
            if (isLetv || isShows){
            	strAppend(midsb, episodetmp, mid,";");
            	strAppend(letvids,episodetmp, transientMap.get("letv_video_id"),";");
            }
			if (isLetv) {
			    strAppend(videoSubNames, episodetmp, transientMap.get("vsubName"),";");
			    strAppend(isPays, episodetmp, transientMap.get("is_pay"),";");
			    strAppend(downloadPlatform, episodetmp, transientMap.get("download_platform"),";");
			    strAppend(payPlatform, episodetmp, transientMap.get("pay_platform"),";");
			   
			    String image =null;
			    try{
                    json = JSON.parseObject(transientMap.get("vImages").toString());
			        if (json.containsKey("400*225")){
			            image = json.getString("400*225");
			        } else if (json.containsKey("400*300")){
			            image = json.getString("400*300");
			        }
			    }catch(Exception e){
			    }
			    strAppend(singleVideoImages, episodetmp, image,";");
            } else {
    			strAppend(exterenalIds,episodetmp,transientMap.get("external_id"),";");
    			strAppend(externalPlayIds,episodetmp,transientMap.get("external_play_id"),";");
                String image =null;
                try {
                    if (transientMap.get("vImages") != null) {
                        json = JSON.parseObject(transientMap.get("vImages").toString());
                        for (int as = 0; as < ARRAy_SORT.length; as++) {
                            if (json.containsKey(ARRAy_SORT[as])) {
                                image = json.getString(ARRAy_SORT[as]);
                                break;
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error("外网单视频流截图下载失败" + e);
                }
                strAppend(singleVideoImages, episodetmp, image,";");
            }
            appendImages(json, cmsImages);
            Object name = transientMap.get("name");
            name = name == null ? "" : name.toString().replace('|', ' ');
            strAppend(tempIntro, transientMap.get("episode"), name, ";");
           
            if (desc) {
				i--;
			}else {
				i++;
			}
		} while ( desc ? i >= end : i<=end );
        if (isLetv) {
            m.put("letvOriginalId", Constants.VRS_ALBUM_PERFIX + m.get("vrsAid").toString());
            if(null != m.get("is_cibn_checked") && "1".equals(m.get("is_cibn_checked").toString())) {  // 有letv源过国广审核该专辑is_cibn_checked = 2
                m.put("is_cibn_checked", 2);
            }
        } else {
            m.put("letvOriginalId", Constants.LESO_ALBUM_PERFIX + m.get("aid").toString());
        }
        if(isCibn || isWasu_tv || isImgoOnTv || isLetv) {
            m.put("pushflag", m.get("video_push_flag"));
        }
		m.put("playurls", tempUrls.toString());
		m.put("intro", tempIntro.toString());
		m.put("deadlinks", deadlinks.toString());
		m.put("global_vid", globalVid.toString());
		m.put("letv_orininal_svids", letv_orininal_svids.toString());
		m.put("videoSubNames", videoSubNames.toString());
		m.put("videoImages", singleVideoImages.toString());
        m.put("isPays", isPays.toString());
        m.put("downloadPlatform", downloadPlatform.toString());
        m.put("payPlatform", payPlatform.toString());
        m.put("exterenalIds", exterenalIds.toString());
        m.put("externalPlayIds", externalPlayIds.toString());
        m.put("sv_mids", midsb.toString());
        m.put("letv_vids", letvids.toString());
        m.put("svids", videoIds.deleteCharAt(videoIds.length() - 1).toString());
        m.put("video_types", videoTypes.deleteCharAt(videoTypes.length() - 1).toString());
        m.put("display_area", Mappings.getAreaMap(source));
        if (videoDurations.length() > 0) {
            m.put("video_durations", videoDurations.deleteCharAt(videoDurations.length() - 1).toString());
        }
		Object currentepisode =m.get("currentEpisode");
	    if ( m.get("lockColumn") != null && m.get("albumepd") !=null) {
	         m.put("episodes", m.get("albumepd").toString()); 
	         logger.info("Use album episodes, aid={},episodes={}",m.get("aid"), m.get("albumepd"));
	    } else {
	        ProcessData.setEpisodes(m,m,videolists);
	    }
	    Object albumepd =  m.get("episodes");
		if (isLetv||"nets".equals(m.get("source").toString())){
			m.put("playStatus", m.get("episodeStatus"));
		}else{
//			if (null!=currentepisode&&null!= albumepd&&albumepd.toString().compareTo(currentepisode.toString()) > 0) {
		    if (m.get("aposter") !=null && StringUtils.isNotBlank(m.get("aposter").toString())) {
		        m.put("poster", m.get("aposter"));
		        m.put("postS2", m.get("aposter"));
		    }
		    if (null!=currentepisode&& StringUtils.isNotBlank(currentepisode.toString())&&null!= albumepd&&StringUtils.isNotBlank(albumepd.toString())
                   &&Integer.parseInt(albumepd.toString()) > Integer.parseInt(currentepisode.toString())) {
		         m.put("playStatus", "0");
		    } else {
	             if (null!=currentepisode && currentepisode.toString().length() >=8) {
	                   m.put("playStatus", m.get("episodeStatus"));
	             } else {
	                 m.put("playStatus", "1");
	             }
		    }
		}
		if (category.equals("4")) {
			m.put("detail_link", m.get("url")==null?null:m.get("url").toString());
		}
		if ("1".equals(m.get("is_pay").toString())) {
			m.put("hasvideo_pc", "1");
			m.put("quality", "高清");
			setCounts(m);
		} else {
			m.put("is_pay", "0");
			if (category.equals("1")) {
				setCounts(m);
			}
		}
		if (isLetv) {
		    m.put("subName", m.get("subTitle"));
		    m.put("quality", m.get("play_stream"));
		}
        String albumImages = m.get("cmsImages") == null ? null : m.get("cmsImages").toString();
        String replaceImg = null;
        if (cmsImages.size() > 0) {
            replaceImg = "," + JSONObject.toJSONString(cmsImages) + "]";
        }
        if (replaceImg != null) {
            if (albumImages != null && albumImages.indexOf("]") > 2) {
                albumImages = albumImages.subSequence(0, albumImages.length() - 1) + replaceImg;
            } else {
                albumImages = replaceImg.replaceFirst(",", "[");
            }
        }
        if(isCibn || isWasu_tv || isImgoOnTv) {
            m.put("cmsImages", this.getTvLicensetransverseImage(vid, m.get("images"), m.get("albumPic")));
        } else {
            m.put("cmsImages", albumImages);
        }

        if(Constants.WEBSITE_EROS.equals(source) || isCibn || isWasu_tv || isImgoOnTv) {
            m.put("album_pay_platform", m.get("pay_platform"));
        }
        if(null == m.get("releaseDate") || m.get("releaseDate").toString().length() != 10) {
            if(null != m.get("screen_year") && m.get("screen_year").toString().length() == 4) {
                m.put("releaseDate", m.get("screen_year").toString() + "-01-01");
            } else {
                m.put("releaseDate", null);
            }
        }
        if (!isLetv) m.put("area", null);
		return "";
	}

	/**
	 * 获得tv牌照方站点源所需横图。优先取自身源，若没有则取其合集下letv源的横图
     * @param videoId String, 站点源video id
	 * @param picCollections Object, 空。或者为存储各种尺寸图片的json格式的字符串,示例：
	 *                               {"ar34":{"120*160":"http://img1.c3.letv.com/ptv/letv_vrs/2011/7/tv/ef5fe41c133e4c5db8ab0795ac0c0bf2.jpg","150*200":"http://img1.c3.letv.com/ptv/letv_vrs/2011/7/tv/5aff552316cf4effaa89bd29707934e1.jpg","96*128":"http://img1.c3.letv.com/ptv/letv_vrs/2011/7/tv/be5314ba124c413dbbbd3488e87f8719.jpg"},"ar970300":{"970*300":"http://i0.letvimg.com/vrs/201205/23/0745969f591140e19b7e52f07068c3ad.jpg"}}
	 * @param albumPic Object, 空。 或为存储各种尺寸图片的json格式的字符串，tv牌照方站点源当前默认该字段为空。示例：
	 *                         http://i3.letvimg.com/lc06_isvrs/201607/03/12/04/3a8a8538-41e5-49e1-b2af-f730e44bf9ad
	 *                         传入本方法前会拼出通用后缀：
	 *                         http://i3.letvimg.com/lc06_isvrs/201607/03/12/04/3a8a8538-41e5-49e1-b2af-f730e44bf9ad/thumb/2_
	 *                         最终使用前需在最后拼上所需的特定尺寸：
	 *                         http://i3.letvimg.com/lc06_isvrs/201607/03/12/04/3a8a8538-41e5-49e1-b2af-f730e44bf9ad/thumb/2_960_540.jpg
	 * @return String, tv牌照方站点源所需横图。为空或出错则返回空字符串:""
	 */
    private String getTvLicensetransverseImage(String videoId, Object picCollections, Object albumPic) {
        if(StringUtils.isBlank(videoId)) {
            return "";
        }
        String result = "";
        try {
            Map<String, String> resultMap = new HashMap<String, String>();
            String picCollectionsJsonString = (String)picCollections;
            if(!StringUtils.isBlank(picCollectionsJsonString)) {
                JSONObject picCollectionsJson = JSON.parseObject(picCollectionsJsonString);
                if(null != picCollectionsJson && null != picCollectionsJson.getJSONObject("ar169")) {
                    JSONObject ar169 = picCollectionsJson.getJSONObject("ar169");
                    for(String size : DownloadMapperService.TV_LICENSE_TRANSVERSE_IMAGE_KEY) {
                        if(!StringUtils.isBlank(ar169.getString(size))) {
                            resultMap.put(size, ar169.getString(size));
                        }
                    }
                }
            }
            String albumPicString = (String)albumPic;
            if(!StringUtils.isBlank(albumPicString)) {
                for(String size : DownloadMapperService.TV_LICENSE_TRANSVERSE_IMAGE_KEY) {
                    if(StringUtils.isBlank(resultMap.get(size))) {
                        resultMap.put(size, albumPicString + size.replace("*", "_") + ".jpg");
                    }
                }
            }
            if(resultMap.size() > 0) {
                List<Map<String, String>> resultList = new ArrayList<Map<String, String>>();
                resultList.add(resultMap);
                result = JSON.toJSONString(resultList);
            }
        } catch(Exception e) {
            logger.error("fail to get tv license transverse image,videoId=" + videoId, e);
            result = "";
        }
        return result;
    }

    /**
     * 返回传入专辑非默认站点源的详情。当前仅会返回tv牌照方站点源
     * @param connectionFromLeso Connection, 作品库数据库连接
     * @param albumDefaultDetailMap Map<String, Object>, 专辑默认站点源详情，包括：
     *                                            1.专辑mata信息
     *                                            2.专辑默认站点源信息
     *                                            3.专辑默认站点源单视频信息
     * @return List<Map<String, Object>>, 为空或出错则返回null
     */
	protected List<Map<String, Object>> getOtherSourceDetailList(Connection connectionFromLeso, Map<String, Object> albumDefaultDetailMap) {
        if(null == connectionFromLeso || null == albumDefaultDetailMap || null == albumDefaultDetailMap.get("source_list") || null == albumDefaultDetailMap.get("aid") || StringUtils.isBlank(albumDefaultDetailMap.get("aid").toString())) {
            return null;
        }
        String sourceList = "";
        try {
            sourceList = ((Map<String, String>)albumDefaultDetailMap.get("source_list")).get(Constants.PUSHFLAG_TV);
        } catch(Exception e) {
            logger.error("fail to get source_list,aid=" + albumDefaultDetailMap.get("aid").toString());
            return null;
        }
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for(String tvLicenseSource : Constants.TV_LICENSE_SOURCE_LIST) {
            try {
                if(sourceList.indexOf(tvLicenseSource) < 0) {
                    continue;
                }
                if(null != albumDefaultDetailMap.get("source") && tvLicenseSource.equals(albumDefaultDetailMap.get("source").toString())) {
                    continue;
                }
                logger.info("have other source detail:" + tvLicenseSource);
                Long albumId = Long.parseLong(albumDefaultDetailMap.get("aid").toString());
                List<Map<String, Object>> tempList = SQLUtil.getLesoAlbumSourceData(connectionFromLeso, "leso.SQL2", albumId, albumId + 1l);
                if(null == tempList || tempList.size() != 1 || null == tempList.get(0)) {
                    continue;
                }
                Map<String, Object> otherSourceDetail = tempList.get(0);
                Map<String, Object> video = SQLUtil.getVideoSourceByAlbumId(connectionFromLeso, tvLicenseSource, albumId);
                if (null == video || null == video.get("vid") || StringUtils.isBlank(video.get("vid").toString())) {
                    continue;
                }
                String is_cibn_checked = null==video.get("is_cibn_checked") ? "" : video.get("is_cibn_checked").toString();
                if("0".equals(is_cibn_checked)) {
                    continue;
                }
                video.put("source_list", albumDefaultDetailMap.get("source_list"));
                video.put("cp_letv_original_id", albumDefaultDetailMap.get("cp_letv_original_id"));
                otherSourceDetail.putAll(video);
                this.mapperVideoList(connectionFromLeso, otherSourceDetail);
                otherSourceDetail.put("letvOriginalId", albumDefaultDetailMap.get("letvOriginalId"));
                otherSourceDetail.put("pushflag", otherSourceDetail.get("video_push_flag"));
                if(null != albumDefaultDetailMap.get("is_cibn_checked") && "2".equals(albumDefaultDetailMap.get("is_cibn_checked").toString()) && null != otherSourceDetail.get("is_cibn_checked") && "1".equals(otherSourceDetail.get("is_cibn_checked").toString())) {  // 有letv源过国广审核该专辑is_cibn_checked = 2
                    otherSourceDetail.put("is_cibn_checked", 2);
                }
                if(null != albumDefaultDetailMap.get("source") && Constants.WEBSITE_LETV.equals(albumDefaultDetailMap.get("source").toString()) && (null == otherSourceDetail.get("cmsImages") || StringUtils.isBlank(otherSourceDetail.get("cmsImages").toString()))) {
                    otherSourceDetail.put("cmsImages", this.getTvLicensetransverseImage(albumDefaultDetailMap.get("vid").toString(), albumDefaultDetailMap.get("images"), albumDefaultDetailMap.get("albumPic")));
                }
                result.add(otherSourceDetail);
            } catch(Exception e) {
                logger.error("getOtherSourceDetailList have errors,aid=" + albumDefaultDetailMap.get("aid").toString(), e);
                result = null;
            }
        }
        if(null != result && result.size() == 0) {
            result = null;
        }
        this.setIsCibnShow(albumDefaultDetailMap, result);
        return result;
    }

	/**
	 * 设置是否上cibn字段。
	 * 同一album_id对应多个详情数据时，按如下规则排序后取排序第一的源置is_cibn_show=1。其他源置is_cibn_show=0:
	 * 1.所有待比较源必须过cibn审核，即is_cibn_checked=1
	 * 2.letv > 其他源免费  > 其他源付费。 其中免费及付费列表内部按默认站点源顺序排序
	 * @param albumDefaultDetailMap Map<String, Object>, 默认站点源详情
	 * @param otherSourceList List<Map<String, Object>>, 非默认站点源详情
	 */
	private void setIsCibnShow(Map<String, Object> albumDefaultDetailMap, List<Map<String, Object>> otherSourceList) {
	    try {
	        // 用于排序的所有待比较源必须过cibn审核，即is_cibn_checked=1 || 2
	        List<Map<String, Object>> baseList = new ArrayList<Map<String, Object>>();
	        if(null != albumDefaultDetailMap.get("is_cibn_checked") && ("1".equals(albumDefaultDetailMap.get("is_cibn_checked").toString()) || "2".equals(albumDefaultDetailMap.get("is_cibn_checked").toString()))) {
	            baseList.add(albumDefaultDetailMap);
	        } else {
	            albumDefaultDetailMap.put("is_cibn_show", 0);
	        }
	        if(null != otherSourceList) {
	            for(Map<String, Object> otherSource : otherSourceList) {
	                if(null != otherSource.get("is_cibn_checked") && ("1".equals(otherSource.get("is_cibn_checked").toString()) || "2".equals(otherSource.get("is_cibn_checked").toString()))) {
	                    baseList.add(otherSource);
	                } else {
	                    otherSource.put("is_cibn_show", 0);
	                }
	            }
	        }
	        if(baseList.size() == 0) {
	            return;
	        }
	        List<Map<String, Object>> sortList = new ArrayList<Map<String, Object>>();
	        String sourceList = ((Map<String, String>)albumDefaultDetailMap.get("source_list")).get(Constants.PUSHFLAG_TV);
	        String[] sourceArray = sourceList.split(",");
	        for(int i = 0; i < sourceArray.length; i++) {
	            for(Map<String, Object> base : baseList) {
	                if(null != base.get("source") && sourceArray[i].equals(base.get("source").toString())) {
	                    sortList.add(base);
	                    break;
	                }
	            }
	        }
	        if(sortList.size() == 0) {
	            return;
	        }
	        sortList.get(0).put("is_cibn_show", 1);
	        if(sortList.size() > 1) {
	            for(int i = 1; i < sortList.size(); i++) {
	                sortList.get(i).put("is_cibn_show", 0);
	            }
	        }
	    } catch(Exception e) {
	        logger.error("set is_cibn_show have errors,aid=" + albumDefaultDetailMap.get("aid").toString(), e);
	    }
    }

    /**
	 * return video resource id.return null if there is no value or catch errors.
	 * if this video's source is letv,return VRS_VIDEO_PERFIX with letv video id;ohterwise return LESO_VIDEO_PERFIX with leso singvideo id.
	 * @param isLetv boolean, 
	 *        true  : source is letv
	 *        false : source is not letv
	 * @param transientMap, singleVideo data selected from database leso
	 * @return String, video resource id
	 */
    private String connectVideoResourceId(Map<String, Object> singleVideoMap, boolean isLetv) {
        if(null == singleVideoMap || null == singleVideoMap.get("svid")) {
            return null;
        }
        String record = null;
        String singleVideoId = singleVideoMap.get("svid").toString();
        try {
            if(isLetv) {
                if(null == singleVideoMap.get("letv_video_id")) {
                    return null;
                }
                String letvVideoId = singleVideoMap.get("letv_video_id").toString();
                record = new StringBuffer("").append(Constants.VRS_VIDEO_PERFIX).append(letvVideoId).toString();
            } else {
                record = new StringBuffer("").append(Constants.LESO_VIDEO_PERFIX).append(singleVideoId).toString();
            }
        } catch(Exception e) {
            logger.error("have erros when try to connect video resource id, video id = " + singleVideoId, e);
            record = null;
        }
        return record;
    }

    private void setPublisher(Object cpId, Connection connToSrc, Map<String, Object> m) {
        String publisher = SQLUtil.getPublisherName(connToSrc, cpId);
        m.put("publisher", publisher);
    }

    private void appendImages(JSONObject json, Map<String, String> cmsImages) {
        if (cmsImages.size() == IMAGES_KEY.length || json == null) {
            return;
        }
        for (String key : IMAGES_KEY) {
            if (cmsImages.containsKey(key)) {
                continue;
            }
            if (json.containsKey(key)) {
                cmsImages.put(key, json.getString(key));
            }
        }
    }

    private ArrayList<Map<String, Object>> getOtherTypeVideo(
            Connection connToSrc, String string, String vid) throws SQLException {
	    ArrayList<Map<String, Object>> records = SQLUtil.getLesoAlbumVideoSourceData(connToSrc, "leso.SQL3", vid,"180002");
        if (records.size() == 0) {
             records = SQLUtil.getLesoAlbumVideoSourceData(connToSrc, "leso.SQL3", vid,"180003");
        }
	    return records;
    }

    private void setCounts(Map<String, Object> m) {
		m.put("dayCount", m.get("vdaycount"));
		m.put("weekCount", m.get("weekCount"));
		m.put("monthCount", m.get("monthCount"));
		m.put("playCount", m.get("playCount"));
	}

	public static void strAppend(StringBuffer sb, Object paramFirst,
			Object paramSeconed, String delimiter) {
		sb.append(paramFirst==null?"":paramFirst.toString());
		sb.append("|");
		sb.append(paramSeconed==null?"":paramSeconed.toString());
		sb.append(delimiter);
	}
}
